import React, { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { marked } from 'marked';
import "../static/css/AddArticle.css";
import { Row, Col, Input, Select, Button, DatePicker, message } from 'antd';
import dayjs from 'dayjs'
import axios from 'axios';
import servicePath from '../config/apiUrl'
const { TextArea } = Input;

const AddArticle = () => {
    const [articleId, setArticleId] = useState(0)  // 文章的ID，如果是0说明是新增加，如果不是0，说明是修改
    const [articleTitle, setArticleTitle] = useState('')   // 文章标题
    const [articleContent, setArticleContent] = useState('')  // markdown的编辑内容
    const [markdownContent, setMarkdownContent] = useState('预览内容') // html内容
    const [introducemd, setIntroducemd] = useState()            // 简介的markdown内容
    const [introducehtml, setIntroducehtml] = useState('等待编辑') // 简介的html内容
    const [showDate, setShowDate] = useState()   // 发布日期
    const [updateDate, setUpdateDate] = useState() // 修改日志的日期
    const [typeInfo, setTypeInfo] = useState([]) // 文章类别信息
    const [selectedType, setSelectType] = useState("请选择类别") // 选择的文章类别

    const navigate = useNavigate();
    const params = useParams();
    const dateFormat = 'YYYY-MM-DD';

    const renderer = new marked.Renderer();
    marked.setOptions({
        renderer: renderer,
        gfm: true,
        pedantic: false,
        sanitize: false,
        tables: true,
        breaks: false,
        smartLists: true,
        smartypants: false
    });

    // 文章内容
    const handleArticleContent = (e) => {
        setArticleContent(e.target.value);
        let html = marked(e.target.value);
        setMarkdownContent(html);
    }

    // 文章简介
    const handleIntroduce = (e) => {
        setIntroducemd(e.target.value);
        let html = marked(e.target.value);
        setIntroducehtml(html);
    }

    useEffect(() => {
        getTypeInfo();
        // 获得文章ID
        let tempId = params.id;
        if (tempId) {
            setArticleId(tempId);
            getArticleById(tempId);
        }
    }, []);

    // 从中台得到文章类别信息
    const getTypeInfo = () => {
        axios({
            method: "get",
            url: servicePath.getTypeInfo,
            header: { 'Access-Control-Allow-Origin': '*' },
            withCredentials: true
        }).then(res => {
            const { code, msg, data } = res.data;

            if (code == 0) {
                data.map(item => {
                    item.label = item.typeName;
                    item.value = item.Id;
                    return item;
                });
                setTypeInfo(data);

            } else if (code == -1) {
                message.error(msg);
                localStorage.removeItem('openId')
                navigate('/');
            }
        })
    }

    // 获取文章列表信息
    const getArticleById = (id) => {
        axios(servicePath.getArticleById + id, { withCredentials: true }).then(res => {
            const { code, data } = res.data;
            if (code === 0) {
                let list = data[0];
                setSelectType(list.typeId);
                setArticleTitle(list.title);
                setArticleContent(list.article_content);
                let articleContentHtml = marked(list.article_content);
                setMarkdownContent(articleContentHtml);
                setIntroducemd(list.introduce);
                let introduceHtml = marked(list.introduce);
                setIntroducehtml(introduceHtml);
                setShowDate(list.addTime);
            }
        });
    }

    // 文章类别
    const handleSelectedType = (value) => {
        setSelectType(value);
    }

    // 发布文章
    const saveArticle = () => {
        if (!selectedType) {
            message.error('必须选择文章类别');
            return;
        } else if (!articleTitle) {
            message.error('博客标题不能为空');
            return;
        } else if (!articleContent) {
            message.error('博客内容不能为空');
            return;
        } else if (!introducemd) {
            message.error('文章简介不能为空');
            return;
        } else if (!showDate) {
            message.error('发布日期不能为空');
            return;
        }
        // message.success('检验通过')
        let data = {}; // 传递到接口的参数
        data.type_id = selectedType;
        data.title = articleTitle;
        data.article_content = articleContent;
        data.introduce = introducemd;
        let datetext = showDate.replace('-', '/') // 把字符串转换成时间戳
        data.addTime = (new Date(datetext).getTime()) / 1000;

        if (articleId == 0) {
            data.view_count = Math.ceil(Math.random() * 100) + 1000;
            axios({
                method: 'post',
                url: servicePath.addArticle,
                data,
                withCredentials: true
            }).then(res => {
                const { code, msg, data: { insertId } } = res.data;
                setArticleId(insertId);
                if (code === 0) {
                    message.success(msg);
                } else {
                    message.error(msg);
                }

            })
        } else {
            data.id = articleId;
            axios({
                method: "post",
                url: servicePath.updateArticle,
                data,
                withCredentials: true
            }).then(res => {
                const { code, msg } = res.data;
                if (code === 0) {
                    message.success(msg);
                } else {
                    message.error(msg);
                }
            });
        }
    }

    return (
        <div>
            <Row gutter={5}>
                <Col span={18}>
                    <Row gutter={10}>
                        <Col span={20}>
                            <Input
                                value={articleTitle}
                                placeholder='请输入博客标题'
                                onChange={e => { setArticleTitle(e.target.value) }}
                                size="large"
                            />
                        </Col>
                        <Col span={4}>
                            &nbsp;
                            <Select
                                defaultValue={selectedType}
                                value={selectedType}
                                onChange={handleSelectedType}
                                options={typeInfo}
                                size="large"
                            />
                        </Col>
                    </Row>
                    <br />
                    <Row gutter={10}>
                        <Col span={12}>
                            <TextArea
                                value={articleContent}
                                className='markdown-content'
                                rows={35}
                                onChange={handleArticleContent}
                                placeholder="文章内容"
                            />
                        </Col>
                        <Col span={12}>
                            <div className='show-html' dangerouslySetInnerHTML={{ __html: markdownContent }}></div>
                        </Col>
                    </Row>
                </Col>
                <Col span={6}>
                    <Row>
                        <Col span={24}>
                            <Button size='large'>暂存文章</Button>&nbsp;
                            <Button type='primary' size='large' onClick={saveArticle}>发布文章</Button>
                            <br />
                        </Col>
                        <Col span={24}>
                            <br />
                            <TextArea
                                value={introducemd}
                                rows={4}
                                placeholder="文章简介"
                                onChange={handleIntroduce}
                            />
                            <br /><br />
                            <div className='introduce-html' dangerouslySetInnerHTML={{ __html: introducehtml }}></div>
                        </Col>
                    </Row>
                    <Row gutter={10}>
                        <Col span={12}>
                            <div className='date-select'>
                                <DatePicker
                                    value={dayjs(showDate, dateFormat)}
                                    onChange={(date, dateString) => setShowDate(dateString)}
                                    placeholder='发布日期'
                                    size="large"
                                />
                            </div>
                        </Col>
                        <Col span={12}>
                            <div className='date-select'>
                                <DatePicker
                                    onChange={(date, dateString) => setUpdateDate(dateString)}
                                    placeholder='修改日期'
                                    size="large"
                                />
                            </div>
                        </Col>
                    </Row>
                </Col>
            </Row>
        </div>
    )
}

export default AddArticle;